package com.alex.common.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.alex.common.persistent.CommonService;

@Controller
@RequestMapping("/common")
public class CommonController {

	@Autowired
	private CommonService commonService;

	private static final String DOMAIN_PACKAGE = "com.alex.demos.domain.";

	private Class<?> getPClaz(String clazName) throws ClassNotFoundException {
		return clazName.indexOf(".") == -1 ? Class.forName(DOMAIN_PACKAGE
				+ clazName) : Class.forName(clazName);
	}

	@RequestMapping(value = "query", method = RequestMethod.GET)
	public String query(String clazName, Integer first, Integer max, Model model)
			throws ClassNotFoundException {
		if (clazName == null) {
			return "toolslib/common";
		}

		List<Map<String, Object>> list = commonService.queryListMap(
				getPClaz(clazName), null, null, first == null ? 0 : first,
				max == null ? 0 : max);
		Map<String, Object> keyMap = list.remove(0);
		model.addAttribute("keyMap", keyMap);
		model.addAttribute("list", list);
		model.addAttribute("pClazName", getPClaz(clazName).getName());
		return "toolslib/common";
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "insert", method = RequestMethod.POST)
	public ModelAndView insert(@RequestParam("class") String pClazName,
			HttpServletRequest request, Model model)
			throws ClassNotFoundException {
		commonService.insert(new HashMap<String, Object>(request
				.getParameterMap()));
		ModelAndView mv = new ModelAndView(new RedirectView("/common/query"),
				"clazName", pClazName);
		return mv;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "update", method = RequestMethod.POST)
	public ModelAndView update(@RequestParam("class") String pClazName,
			@RequestParam("id") Long id, HttpServletRequest request)
			throws ClassNotFoundException {
		commonService.update(
				new HashMap<String, Object>(request.getParameterMap()), id);
		ModelAndView mv = new ModelAndView(new RedirectView("/common/query"),
				"clazName", pClazName);
		return mv;
	}

	@RequestMapping(value = "delete", method = RequestMethod.GET)
	public ModelAndView delete(@RequestParam("class") String pClazName,
			@RequestParam("id") Long id) throws ClassNotFoundException {
		commonService.delete(Class.forName(pClazName), id);
		ModelAndView mv = new ModelAndView(new RedirectView("/common/query"),
				"clazName", pClazName);
		return mv;
	}

}